<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
* 微站模型
*/
class msm_weixin_mp extends ms_model
{
	public $table = 'dbpre_weixin_mp';
	public $key = 'id';
	public $model_flag = 'weixin';

	public function __construct()
	{
		parent::__construct();
		$this->model_flag = 'weixin';
		$this->modcfg = $this->variable('config');
		$this->init_field();
	}

	/**
	 * 表单提交时需要的字段和过滤
	 */
	public function init_field()
	{
		$this->add_field('role,role_id,wechat,token,appid,appsecret,app_encodekey,app_encodetype,config');
		$this->add_field_fun('role_id', MF_INT_KEY);
		$this->add_field_fun('role,wechat,token,appid,appsecret', MF_TEXT);
		$this->add_field_fun('config', MF_TEXT);
	}

	/**
	 * 获取网站（总站）的微信配置信息
	 * 通过主题id获取微信配置信息
	 * @return array|null
	 */
	public function read_site()
	{
		return $this->db->from($this->table)->where(array('role'=>'site','role_id'=>0))->get_one();
	}

	/**
	 * 通过主题id获取微信配置信息
	 * @param  integer $sid 主题ID
	 * @return array|null
	 */
	public function read_by_sid($sid)
	{
		return $this->db->from($this->table)->where(array('role'=>'subject','role_id'=>$sid))->get_one();
	}

	/**
	 * 获取分站城市的微信配置信息
	 * @param  integer $city_id 城市ID
	 * @return array|null
	 */
	public function read_by_city_id($city_id)
	{
		return $this->db->from($this->table)->where(array('role'=>'site','role_id'=>$city_id))->get_one();
	}

	public function save_access_token($id, $access_token, $expires_in)
	{
		return $this->db->from($this->table)
			->where('id',$id)
			->set(array('access_token'=>$access_token,'expires_in'=>$expires_in))
			->update();
	}

	public function check_post(&$post, $keyid = FALSE)
	{
		$post['wechat'] = trim($post['wechat']);
		$post['token'] = trim($post['token']);
		if(!$post['role']) return $this->add_error('对不起，您未指定绑定公众平台的对象类型。');
		if(!$post['role_id'] && $post['role'] != 'site') return $this->add_error('对不起，您指定写绑定公众平台的对象ID。');
		if(!$post['wechat']) return $this->add_error('对不起，您未填写微信公众号。');
		if(!$post['token']) return $this->add_error('对不起，您未填写令牌参数(Token)。');
		if($post['config']['encode_type']=='1' && !$post['config']['encode_key']) {
			return $this->add_error('请填写消息加解密密钥。');
		}

		//检测是否已经存在微信帐号
		if($data = $this->exists_wechat($post['wechat'])) {
			if(!$keyid || ($keyid > 0 && $keyid != $data['id'])) {
				return $this->add_error('对不起，您填写的微信公众号已存在。');
			}
		}
		return $post;
	}

	/**
	 * 微信号是否已经存在
	 * @param  string $wechat 微信号
	 * @return [type]         [description]
	 */
	public function exists_wechat($wechat)
	{
		return $this->db->from($this->table)->where('wechat', $wechat)->get_one();
	}

	/**
	 * 
	 * @param  integer $id     公众号表ID
	 * @param  string $status 'on' Or 'off'
	 * @param  string $message 提醒主题管理员
	 * @return integer         跟新成功=1，未更新=0
	 */
	public function update_on_off($id, $status, $message = '')
	{
		$status = $status=='on'?1:-1;
		$data = $this->read($id);
		if(!$data) return $this->add_error('更新数据不存在！');

		$result = $this->db->from($this->table)
			->where('id', $id)
			->set('status', $status)
			->update();

		if(!$result) return false;
		if($data['role']!='subject') return $result;

		$my_mdl = $this->loader->model('item:mysubject');
		$uids = $my_mdl->get_uids($data['role_id'], 'owner');
		if(!$uids) return true;

		if($status == '-1') {
			$notice = lang('weixin_notice_mp_off', array($data['wechat'], $message?$message:'管理员未填写'));
		} elseif($status == '1') {
			$notice = lang('weixin_notice_mp_on', $data['wechat']);
		}

		$notice_mdl = $this->loader->model('member:notice');
		foreach ($uids as $uid) {
			$notice_mdl->save($uid, $this->model_flag, 'mp_on_off', $notice);
		}

		return true;
	}

	/**
	 * 删除一条数据
	 * @param  integer $id      微信号绑定记录ID
	 * @param  string $message 删除理由
	 * @return booean          1 or 0
	 */
	public function delete($id, $message)
	{
		if(!$id) return;

		$data = $this->read($id);
		if(!$data) return $this->add_error('删除的数据不存在。');

		if(!parent::delete($id)) return false;

		$cmd_mdl	= _G('loader')->model('weixin:custom_cmd');
		//删除自定义指令数据
		$cmd_mdl->delete_by_mp_id($id);

		if($data['role'] != 'subject' || !$data['role_id']) return true;

		//删除掉微站数据
		$sid = $data['role_id'];
		$site_mdl = _G('loader')->model('weixin:site');
		$site_mdl->delete_by_sid($sid);

		if(!$message) return true;

		$my_mdl	= $this->loader->model('item:mysubject');
		$uids 	= $my_mdl->get_uids($sid, 'owner');
		if(!$uids) return true;

		//发送提醒信息
		$notice = lang('weixin_notice_mp_delete', array($data['wechat'], $message));
		$notice_mdl = $this->loader->model('member:notice');
		foreach ($uids as $uid) {
			$notice_mdl->save($uid, $this->model_flag, 'mp_delete', $notice);
		}
	}

	public function delete_by_sid($sid)
	{
		$where = array();
		$where['role'] = 'subject';
		$where['role_id'] = $sid;
		$mp = $this->db->from($this->table)->where($where)->get_all();
		if(!$mp) return false;
		foreach ($mp as $value) {
			$this->delete($value['id']);
		}
	}

	//保存更新之前
	protected function _save_befor()
	{
		if($this->_save_data['config']) {
			$this->loader->helper('mxml');
			$this->_save_data['config'] = mxml::from_array($this->_save_data['config']);
		} else {
			$this->_save_data['config'] = '';
		}
	}

}

/** end **/